package flc.ast.activity;

import static com.stark.imgocr.api.VerifyMethod.APPCODE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.imgocr.ImgOcrEntry;
import com.stark.imgocr.api.Config;
import com.stark.imgocr.api.IRetCallback;
import com.stark.imgocr.api.bean.OcrRetBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.MyRecRecordBean;
import flc.ast.databinding.ActivityTakePicTransBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.apis.ApiManager;
import stark.common.apis.base.ImgPlantRet;
import stark.common.base.IReqRetCallback;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class TakePicTransActivity extends BaseAc<ActivityTakePicTransBinding> {


    @Override
    protected int onCreate() {
        return R.layout.activity_take_pic_trans;
    }

    @Override
    protected void initView() {
        mDataBinding.ivTakePicTransBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.ivTakePhoto.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivTakePhoto://拍摄
                mDataBinding.cameraView.takePictureSnapshot();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                mDataBinding.tvRecTip.setText(getString(R.string.rec_ing));
                mDataBinding.tvRecTip.setVisibility(View.VISIBLE);
                mDataBinding.llRecIng.setVisibility(View.VISIBLE);
                Animation animation = new RotateAnimation(0, 359, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(1000);
                animation.setRepeatCount(1000);
                animation.setFillAfter(true);//设置为true，动画转化结束后被应用
                mDataBinding.ivRecTip.startAnimation(animation);//开始动画
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        Config config = Config.verifyByAppCode(String.valueOf(APPCODE));
                        ImgOcrEntry.init(config);
                        ImgOcrEntry.getOcrReqManager().urlImages(TakePicTransActivity.this, bitmap, new IRetCallback<List<OcrRetBean.Word>>() {
                            @Override
                            public void onRet(String errCode, String errMsg, @Nullable List<OcrRetBean.Word> wordList) {
                                mDataBinding.llRecIng.setVisibility(View.GONE);
                                mDataBinding.ivRecTip.clearAnimation();//结束动画
                                if (isDestroyed()) {
                                    mDataBinding.tvRecTip.setText(getString(R.string.rec_def));
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mDataBinding.tvRecTip.setVisibility(View.GONE);
                                        }
                                    }, 2000);
                                    return;
                                }
                                if (wordList == null) {
                                    mDataBinding.tvRecTip.setText(getString(R.string.rec_def));
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mDataBinding.tvRecTip.setVisibility(View.GONE);
                                        }
                                    }, 2000);
                                    return;
                                }
                                mDataBinding.tvRecTip.setVisibility(View.GONE);
                                mDataBinding.llRecIng.setVisibility(View.GONE);
                                StringBuilder stringBuilder = new StringBuilder();
                                OcrRetBean.Word word = null;
                                for (int i = 0; i < wordList.size(); i++) {
                                    word = wordList.get(i);
                                    stringBuilder.append(word.getWords());
                                    if (i != wordList.size() - 1) {
                                        stringBuilder.append("\n");
                                    }
                                }
                                dismissDialog();
                                RecTransActivity.sResult = stringBuilder.toString();
                                startActivity(RecTransActivity.class);
                            }
                        });
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

}